package com.candy.db.generator.utils;

import com.candy.db.generator.config.GlobalConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * Created by yantingjun on 2016/7/14.
 */
public class FreeMarkerKit {
//    private static Configuration cfg = null;
    public static Configuration getConfiguration(){
        Configuration cfg = new Configuration();
        try {
            File file = new File("templates"+File.separator+ GlobalConfig.templateGroup);
            cfg.setDirectoryForTemplateLoading(file);
        } catch (IOException e) {
            LogKit.error("template group:"+GlobalConfig.templateGroup+" doesn`t exists!");
            System.exit(0);
        }
        return cfg;
    }

    public static void make(Object rootMap,String template,String outFilePath){
        FileWriter writer = null;
        try {
            Template tem = getConfiguration().getTemplate(template);
            writer = new FileWriter(outFilePath);

            tem.process(rootMap, writer);
            writer.flush();
            LogKit.debug("generate file:"+outFilePath+" using template:"+template);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOUtils.closeQuietly(writer);
        }
    }
}
